from app.extensions import db


class User(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    openid = db.Column(db.String(64), unique=True, nullable=False, comment='微信 openid')
    username = db.Column(db.String(64), nullable=False, default='默认昵称', comment='昵称')
    points = db.Column(db.Integer, nullable=False, default=0, comment='积分')
    school = db.Column(db.String(64), nullable=True, comment='所属学校')
    class_name = db.Column(db.String(64), nullable=True, comment='所属班级')
    avatar_url = db.Column(db.String(255), nullable=False, default='avatars/default_avatar.jpg', comment='用户头像路径')
    created_at = db.Column(db.DateTime, server_default=db.func.now(), comment='注册时间')
    image_records = db.relationship('ImageRecord', backref='user', lazy=True, cascade='all, delete-orphan')

    def to_dict(self):
        return {
            'id': self.id,
            'openid': self.openid,
            'username': self.username,
            'points': self.points,
            'avatar_url': self.avatar_url,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S')
        }

    @staticmethod
    def get_user_by_openid(openid):
        return User.query.filter_by(openid=openid).first()

    @staticmethod
    def add_points(openid, points_to_add):
        """
        根据 openid 查找用户并增加积分
        :param openid: 微信 openid
        :param points_to_add: 要添加的积分（整数）
        :return: 更新后的用户对象，如果用户不存在则返回 None
        """
        user = User.query.filter_by(openid=openid).first()
        if user:
            user.points += points_to_add
            db.session.commit()
            return user
        return None
